package com.bjpowernode.validator.web;

import com.bjpowernode.validator.enums.ErrorCode;
import com.bjpowernode.validator.vo.ResultVO;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Path;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * ClassName:ControllerAdvice
 * Package:com.bjpowernode.validator.web
 * Description: 描述信息
 *
 * @date:2022/3/19 14:22
 * @author:动力节点
 */


@ControllerAdvice(basePackages = "com.bjpowernode.validator.controller")
@ResponseBody
public class CtrlAdvice {

    @ExceptionHandler
    public ResultVO exceptionHandler(MethodArgumentNotValidException e){

        Map<String, String> collect = e.getBindingResult().getFieldErrors().stream()
                .collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
        return ResultVO.error(ErrorCode.PARAM_ERROR,collect);
    }

    /**
     * 验证写在server层会爆ConstraintViolationException
     * @param e
     * @return
     */
    @ExceptionHandler
    public ResultVO exceptionHandler(ConstraintViolationException e){

        Map<Path, String> collect = e.getConstraintViolations().stream()
                .collect(Collectors.toMap(ConstraintViolation::getPropertyPath, ConstraintViolation::getMessage));
        return ResultVO.error(ErrorCode.PARAM_ERROR,collect);
    }

}
